import React, { useState } from 'react';
import { StyleSheet, View, Image, TouchableOpacity, KeyboardAvoidingView, Platform, ScrollView, Alert } from 'react-native';
import { TextInput, Button } from 'react-native-paper';
import { useRouter } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';

import { useAuth } from '@/contexts/AuthContext';

import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

export default function RegisterScreen() {
  const colorScheme = useColorScheme();
  const router = useRouter();
  const tintColor = Colors[colorScheme ?? 'light'].tint;

  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [secureTextEntry, setSecureTextEntry] = useState(true);
  const [confirmSecureTextEntry, setConfirmSecureTextEntry] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const { register, login } = useAuth();

  // 表单验证函数
  const validateEmail = (email: string) => {
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    return emailRegex.test(email);
  };

  const validatePassword = (password: string) => {
    // 密码至少8位，包含字母和数字
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
    return passwordRegex.test(password);
  };

  const validateAge = (age: string) => {
    const ageNum = parseInt(age);
    return !isNaN(ageNum) && ageNum >= 18 && ageNum <= 120;
  };

  const handleRegister = async () => {
    console.log('注册按钮被点击');
    
    // 防止重复点击
    if (isLoading) {
      console.log('注册按钮已被点击，正在处理中...');
      return;
    }
    
    // 表单验证
    if (!name || !age || !email || !password || !confirmPassword) {
      Alert.alert('错误', '请填写所有必填字段');
      return;
    }

    // 验证邮箱格式
    if (!validateEmail(email)) {
      Alert.alert('错误', '请输入有效的邮箱地址');
      return;
    }

    // 验证年龄
    if (!validateAge(age)) {
      Alert.alert('错误', '请输入有效的年龄（18-120岁）');
      return;
    }

    // 验证密码强度
    if (!validatePassword(password)) {
      Alert.alert('错误', '密码至少需要8位，且包含字母和数字');
      return;
    }

    if (password !== confirmPassword) {
      Alert.alert('错误', '两次输入的密码不一致');
      return;
    }

    console.log('开始注册过程，发送数据:', { name, age, email });
    setIsLoading(true);
    try {
      console.log('调用register函数');
      const success = await register(name, age, email, password);
      console.log('注册结果:', success);
      
      if (success) {
        // 不使用Alert，直接尝试登录
        try {
          // 自动登录
          const loginSuccess = await login(email, password);
          console.log('自动登录结果:', loginSuccess);
          
          if (loginSuccess) {
            // 登录成功后，延迟执行导航
            console.log('登录成功，准备导航到个人资料设置页面');
            setTimeout(() => {
              console.log('导航到个人资料设置页面');
              router.push('/profile-setup');
            }, 1000);
          } else {
            // 如果自动登录失败，延迟导航到登录页面
            console.log('登录失败，导航到登录页面');
            setTimeout(() => {
              router.push('/auth/login');
            }, 1000);
          }
        } catch (error) {
          console.error('自动登录失败:', error);
          setTimeout(() => {
            router.push('/auth/login');
          }, 1000);
        }
      } else {
        // 使用setTimeout确保Alert在主线程上运行
        setTimeout(() => {
          Alert.alert('注册失败', '请稍后重试');
        }, 100);
      }
    } catch (error) {
      console.error('注册错误详情:', error);
      // 使用setTimeout确保Alert在主线程上运行
      setTimeout(() => {
        Alert.alert('错误', '注册过程中发生错误，请重试');
      }, 100);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}>
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.header}>
            <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
              <MaterialCommunityIcons name="arrow-left" size={28} color={tintColor} />
            </TouchableOpacity>
            <ThemedText style={styles.headerTitle}>注册账号</ThemedText>
            <View style={styles.placeholder} />
          </View>

          <View style={styles.formContainer}>
            <TextInput
              label="姓名"
              value={name}
              onChangeText={setName}
              mode="outlined"
              style={styles.input}
              left={<TextInput.Icon icon="account" color={tintColor} />}
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />

            <TextInput
              label="年龄"
              value={age}
              onChangeText={setAge}
              mode="outlined"
              style={styles.input}
              keyboardType="numeric"
              left={<TextInput.Icon icon="calendar" color={tintColor} />}
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />

            <TextInput
              label="邮箱"
              value={email}
              onChangeText={setEmail}
              mode="outlined"
              style={styles.input}
              autoCapitalize="none"
              keyboardType="email-address"
              left={<TextInput.Icon icon="email" color={tintColor} />}
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />

            <TextInput
              label="密码"
              value={password}
              onChangeText={setPassword}
              mode="outlined"
              style={styles.input}
              secureTextEntry={secureTextEntry}
              left={<TextInput.Icon icon="lock" color={tintColor} />}
              right={
                <TextInput.Icon
                  icon={secureTextEntry ? 'eye-off' : 'eye'}
                  color={tintColor}
                  onPress={() => setSecureTextEntry(!secureTextEntry)}
                />
              }
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />

            <TextInput
              label="确认密码"
              value={confirmPassword}
              onChangeText={setConfirmPassword}
              mode="outlined"
              style={styles.input}
              secureTextEntry={confirmSecureTextEntry}
              left={<TextInput.Icon icon="lock-check" color={tintColor} />}
              right={
                <TextInput.Icon
                  icon={confirmSecureTextEntry ? 'eye-off' : 'eye'}
                  color={tintColor}
                  onPress={() => setConfirmSecureTextEntry(!confirmSecureTextEntry)}
                />
              }
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />

            <Button
              mode="contained"
              onPress={handleRegister}
              disabled={isLoading}
              style={styles.registerButton}
              labelStyle={styles.registerButtonText}
              loading={isLoading}
            >
              注册
            </Button>

            <View style={styles.loginContainer}>
              <ThemedText style={styles.loginText}>已有账号？</ThemedText>
              <TouchableOpacity onPress={() => router.push('/auth/login')}>
                <ThemedText style={styles.loginLink}>立即登录</ThemedText>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 20,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: 60,
    paddingBottom: 20,
  },
  backButton: {
    padding: 5,
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  placeholder: {
    width: 38, // 与返回按钮宽度相同，用于居中标题
  },
  formContainer: {
    width: '100%',
    marginTop: 20,
  },
  input: {
    marginBottom: 15,
    fontSize: 16,
    height: 60,
  },
  registerButton: {
    padding: 5,
    backgroundColor: '#0a7ea4',
    marginTop: 10,
  },
  registerButtonText: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  loginContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 20,
  },
  loginText: {
    fontSize: 16,
  },
  loginLink: {
    fontSize: 16,
    color: '#0a7ea4',
    fontWeight: 'bold',
    marginLeft: 5,
  },
});